/*
 * @Description: 检索结果页高级列表显示
 * @Author: Zzt
 * @Date: 2022-08-25 11:42:45
 * @LastEditTime: 2023-03-10 16:46:18
 */

import { ReactText, SetStateAction, useEffect, useMemo, useState } from 'react';
import { Button, Divider, Dropdown, Menu, Modal, Form, Radio, message, Space } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import ProList from '@ant-design/pro-list';
import LevelLayoutDialog from '@/components/LevelLayoutDialog';
import FullTitle from './FullTitle';
import { Belonging } from './dialog/BelongPopUp';
import { submitAadvanceSearch, submitEntrySearch, submitFullTextSearch } from '@/api/search';
import { useSearchResultContext } from '../contexts/SearchResultContext';
import BorrowDialog, { IStaticInfo } from '@/components/BorrowDialog';
import { selectItemByKey } from '@/utils/list';
import type { ItemType } from 'antd/lib/menu/hooks/useItems';
import styles from '../styles/nav.module.scss';
import classNames from 'classnames/bind';
import ApplyRightDialog from './dialog/ApplyRightDialog';
const cx = classNames.bind(styles);

const ResultInfo = ({ info, fields, type }: any) => {
  return (
    <Space size={type ? 'small' : 'large'} direction={type}>
      {fields.map((item: any) => (
        <Form.Item label={item.field_desc} key={item.field_desc}>
          <span dangerouslySetInnerHTML={{ __html: info[item.field_name] }}></span>
        </Form.Item>
      ))}
    </Space>
  );
};

// const ResultTitle = (info: any) => {};
const ResultList = ({ info, type }: any) => {
  console.log('result info', info);
  const { data, downLevel, upLevel, level } = info;
  const { getListQueryData } = useSearchResultContext();
  const [fondsName, archiveTypeName] = level.fullName.split('-');
  const currentCoordinate: IStaticInfo = {
    atCode: downLevel?.atCode || upLevel?.atCode,
    atType: downLevel?.atType || upLevel?.atType,
    level: level.level,
    fondsName,
    archiveTypeName
  };

  /* 判断是否折叠 */
  const [show, setShow] = useState(2);

  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: info.data.pageSize
  });

  const [total, setTotal] = useState(0);

  /* 电子原文弹窗title */
  const [textTitle, setTextTitle] = useState('');
  /* 所属层级弹窗 */
  const [visible, setVisible] = useState(false);

  const [title, setTitle] = useState('');
  // 选中的条目
  const [selectData, setSelectData] = useState(null);
  // 借阅弹窗标志
  const [borrowVisible, setBorrowVisible] = useState(false);
  /* 权限申请 */
  const [jurisdictionVisible, setJurisdictionVisible] = useState(false);

  useEffect(() => {
    if (listQuery.pageNo === 1) return;
    setShow(type);
    setTotal(info.data.totalCount);
    if (type === 3) {
      submitAadvanceSearch({ ...listQuery, param: info.searchRequest }).then((res: any) => {
        const { data } = res;
        getListQueryData(data);

        console.log(data);
      });
    }
    if (type === 2 || type === 11) {
      submitFullTextSearch({ ...listQuery, param: info.searchRequest }).then((res: any) => {
        const { data } = res;
        getListQueryData(data);
      });
    }
    if (type === 1 || type === 6) {
      submitEntrySearch({ ...listQuery, param: info.searchRequest }).then((res: any) => {
        const { data } = res;
        getListQueryData(data);
      });
    }
  }, [listQuery]);

  // 切换页码触发
  const pageChange = (page: number, _pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page
    }));
  };

  // 编辑弹窗状态
  const [previewDialogVisible, setPreviewDialogVisible] = useState(false);

  // 编辑弹窗数据
  const [editData, setEditData] = useState({});

  // 表格列表
  const onClick = (record: any) => {
    console.log('点击', record);
    setEditData(record);
    setPreviewDialogVisible(true);
    setTextTitle(record.name);
  };
  const showBorrowDialog = () => {
    if (selectedRowKeys.length > 0) {
      const list = data?.results || [];
      const selectRows = selectedRowKeys.map((key) => selectItemByKey(key, list, 'row_id'));
      setSelectData(selectRows);
      setBorrowVisible(true);
    } else {
      message.info('请选择要借阅的文档');
    }
  };
  const showJurisdiction = () => {
    if (selectedRowKeys.length > 0) {
      const list = data?.results || [];
      const selectRows = selectedRowKeys.map((key) => selectItemByKey(key, list, 'row_id'));
      setSelectData(selectRows);
      setJurisdictionVisible(true);
    } else {
      message.info('请选择要申请权限的文档');
    }
  };
  // const { dataSource } = info;
  const onHierarchy = (title: any) => {
    setVisible(true);
    setTitle(title);
  };

  // 气泡所属
  const content = (dataIndex: any) => {
    return <Belonging dataIndex={dataIndex} />;
  };

  /*
   更多著录信息弹窗
   */
  const infoMore = (value: any) => {
    Modal.info({
      title: '著录信息',
      content: (
        <div>
          <ResultInfo info={value} fields={info.fields} type="vertical" />
        </div>
      ),
      onOk() {},
      okText: '确认',
      icon: false
    });
  };

  /*
  整理表格数据
   */
  const dataSource = data.results.map((item: any, index: any) => {
    return {
      id: item.row_id,
      title: <FullTitle dataIndex={item} content={content} info={info} type={type} />,
      /* 判断显示表头，视频暂时屏蔽 */
      // show === 2 ? (
      //   <FullTitle dataIndex={item} content={content} />
      // ) : (
      //   <EntryTitle
      //     fields={info.fields}
      //     ResultInfo={ResultInfo}
      //     message={TopThreeIn}
      //     dataIndex={item}
      //     onHierarchy={onHierarchy}
      //     infoMore={infoMore}
      //     content={content}
      //   />
      // ),
      description:
        show === 11 ? (
          <div className={cx('copyText')}>
            <span dangerouslySetInnerHTML={{ __html: item.file_txt }} />
          </div>
        ) : (
          <div style={{ display: 'flex' }}>
            <ResultInfo info={item} fields={info.fields.slice(0, 3)} />
            {info.fields.length > 3 ? (
              <Button type="link" onClick={() => infoMore(item)}>
                更多著录
              </Button>
            ) : (
              ''
            )}
          </div>
        )
      /* 区分全文和条目检索结果，暂时屏蔽 */
      // show === 1 ? (
      //   <div style={{ display: 'flex' }}>
      //     <ResultInfo key={item.row_id} info={TopThreeIn(item)} fields={info.fields} />
      //     {info.fields.length > 3 ? (
      //       <Button type="link" onClick={() => infoMore(item)}>
      //         更多著录
      //       </Button>
      //     ) : (
      //       ''
      //     )}
      //   </div>
      // ) : (
      //   <Table
      //     columns={columns}
      //     showHeader={false}
      //     dataSource={item.data}
      //     onRow={(record) => {
      //       return {
      //         onClick: () => {
      //           onClick(record);
      //         }
      //       };
      //     }}
      //   />
      // )
    };
  });

  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);

  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: SetStateAction<any[]>) => setSelectedRowKeys(keys)
  };
  /*
  利用按钮下拉菜单
   */
  const MenuList: ItemType[] = [
    {
      key: 'borrow',
      label: '借阅利用',
      onClick: () => {
        showBorrowDialog();
      }
    },
    {
      key: 'jurisdiction',
      label: '权限申请',
      onClick: () => {
        showJurisdiction();
      }
    },
    { key: 'copy', label: '复制申请' },
    { key: 'download', label: '下载' }
  ];

  const applyMenu = <Menu items={MenuList} />;

  const useSort = (
    <div className={cx('useSort')}>
      <Form>
        <Form.Item label="创建时间">
          <Radio.Group>
            <Radio.Button value="a">正序</Radio.Button>
            <Radio.Button value="b">倒序</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="开放时间">
          <Radio.Group>
            <Radio.Button value="a">正序</Radio.Button>
            <Radio.Button value="b">倒序</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="查询频次">
          <Radio.Group>
            <Radio.Button value="high">高</Radio.Button>
            <Radio.Button value="low">低</Radio.Button>
          </Radio.Group>
        </Form.Item>
      </Form>
    </div>
  );

  return (
    <div>
      <ProList<{ title: string }>
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
        split={true}
        toolBarRender={(action) => {
          return [
            <Button key="3" type="primary">
              收藏
            </Button>,
            <Button key="3" type="primary">
              档案篮
            </Button>,
            <Dropdown overlay={useSort}>
              <Button key="3" type="primary">
                排序
                <DownOutlined />
              </Button>
            </Dropdown>,
            <Dropdown overlay={applyMenu}>
              <Button key="3" type="primary">
                申请
                <DownOutlined />
              </Button>
            </Dropdown>,
            <Button
              key="3"
              type="primary"
              onClick={() => {
                console.log('toolbar render action', action);
              }}
            >
              打印
            </Button>,
            <Button key="3" type="primary">
              导出
            </Button>,
            <Button key="3" type="primary">
              下载
            </Button>,
            <Divider type="vertical" />,
            <Button key="3" type="primary">
              筛选
            </Button>
          ];
        }}
        metas={{
          title: {},
          description: {}
        }}
        /* 展开显示，暂时屏蔽 */
        // expandable={
        //   show === 1
        //     ? {}
        //     : {
        //         expandedRowKeys,
        //         defaultExpandAllRows: false,
        //         onExpandedRowsChange: setExpandedRowKeys
        //       }
        // }
        rowKey="id"
        headerTitle={
          <div>
            以下是相关档案列表 | 为您找到相关结果约 {info.statsInfo.total}
            个，本次检索耗时 {info.statsInfo.time}ms
          </div>
        }
        rowSelection={rowSelection}
        dataSource={dataSource}
      />
      {/* 预览弹窗 */}
      {/* {useMemo(
        () => (
          <>
            <Preview
              visible={previewDialogVisible}
              title={textTitle}
              data={editData}
              list={list}
              onClose={() => {
                setPreviewDialogVisible(false);
              }}
            />
          </>
        ),
        [previewDialogVisible]
      )} */}

      {/* 所属层级弹窗 */}
      {useMemo(
        () => (
          <LevelLayoutDialog
            atId={0}
            title={title}
            visible={visible}
            onClose={() => setVisible(false)}
          />
        ),
        [visible]
      )}

      {/* 借阅层级弹窗 */}
      {useMemo(
        () => (
          <BorrowDialog
            title="借阅申请"
            visible={borrowVisible}
            data={selectData}
            staticInfo={currentCoordinate}
            onClose={() => setBorrowVisible(false)}
          />
        ),
        [borrowVisible]
      )}
      {/* 权限申请 */}
      {useMemo(
        () => (
          <ApplyRightDialog
            title="借阅申请"
            visible={jurisdictionVisible}
            data={selectData}
            staticInfo={currentCoordinate}
            onClose={() => setJurisdictionVisible(false)}
          />
        ),
        [jurisdictionVisible]
      )}
    </div>
  );
};
export default ResultList;
